
package cn.bytecollege.admin.filter;

import cn.bytecollege.common.constant.Resource;
import com.google.code.kaptcha.Constants;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebFilter(filterName = "AdminLoginFilter",servletNames = "AdminLoginController")
public class AdminLoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String method = req.getMethod();

        if (method.equalsIgnoreCase("post")){
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String validCode = request.getParameter("validCode");
            String msg = null;

            Pattern usernamePattern = Pattern.compile("\\w{5,12}");
            Matcher usernameMatcher = usernamePattern.matcher(username);
            if (!usernameMatcher.matches()){
                //账号不合法
                msg = "请重新输入,账号格式为5到12位的数字，字母，下划线";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/login.jsp").forward(request,response);
                return;
            }
            Pattern passwordPattern = Pattern.compile("\\d{4,12}");
            Matcher passwordMatcher = passwordPattern.matcher(password);
            if (!passwordMatcher.matches()){
                //密码不合法
                msg = "请重新输入,密码格式为4到12位的数字";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/login.jsp").forward(request,response);
                return;
            }
            HttpSession session = req.getSession();
            String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (!validCode.equalsIgnoreCase(code)){
                msg = "验证码不正确";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/login.jsp").forward(request,response);
                return;
            }
            chain.doFilter(request,response);
        }else {
            chain.doFilter(request, response);
        }

    }
}
